package com.huweilong.tingshu.repository;

import com.huweilong.tingshu.data_object.UserDO;
import com.huweilong.tingshu.util.DBUtil;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author 是阿秋啊
 * @date 2022/07/20 11:10
 **/
public class UserRepo {
    @SneakyThrows //lombok,可以让我们不添加throws也可以正常的抛出异常
    public void insert(UserDO userDO) {
        //数据库的插入操作
        String sql = "insert into users (username,password) values(?, ?)";
        try(Connection c = DBUtil.connection()) {
            try(PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)){
                ps.setString(1,userDO.username);
                ps.setString(2,userDO.password);
                // TODO:项目遗留问题,如果注册用户名相同会直接报错,但是因为注册用的是form表单形式提交,没有json所以更改起来有点麻烦
                ps.executeUpdate();

                //通过自增id作为uid
                try(ResultSet rs = ps.getGeneratedKeys()){
                    rs.next();
                    userDO.uid = rs.getInt(1);
                }
            }
        }
    }
    @SneakyThrows
    public UserDO selectOneByUsername(String username) {
        String sql = "select uid,username,password from users where username = ?";
        try(Connection c = DBUtil.connection()) {
            try(PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1,username);

                try(ResultSet rs = ps.executeQuery()) {
                    if (!rs.next()){
                        return null;
                    }
                    return new UserDO(
                            rs.getInt("uid"),
                            rs.getString("username"),
                            rs.getString("password")
                    );
                }
            }
        }
    }
}